package cn.leftshine.readme.activity;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.ColorStateList;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.design.widget.Snackbar;
import android.support.v4.app.FragmentActivity;
import android.support.v4.widget.NestedScrollView;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.view.menu.MenuBuilder;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.JavascriptInterface;
import android.webkit.ValueCallback;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.maning.imagebrowserlibrary.MNImageBrowser;
import com.maning.imagebrowserlibrary.MNImageBrowserActivity;
import com.maning.imagebrowserlibrary.listeners.OnClickListener;
import com.maning.imagebrowserlibrary.listeners.OnLongClickListener;
import com.maning.imagebrowserlibrary.listeners.OnPageChangeListener;
import com.maning.imagebrowserlibrary.model.ImageBrowserConfig;
import com.yanzhenjie.permission.Action;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.FileProvider;
import com.yanzhenjie.permission.Permission;

import java.io.File;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

import cn.leftshine.readme.R;
import cn.leftshine.readme.activity.base.BaseActivity;
import cn.leftshine.readme.helper.GlideImageEngine;
import cn.leftshine.readme.helper.SettingsHelper;
import cn.leftshine.readme.helper.ThemeInfoHelper;
import cn.leftshine.readme.utils.DateTool;
import cn.leftshine.readme.utils.FileUtils;
import cn.leftshine.readme.utils.HTMLTool;
import cn.leftshine.readme.view.DownLoadProgressbar;
import solid.ren.skinlibrary.SkinLoaderListener;
import solid.ren.skinlibrary.loader.SkinManager;
import solid.ren.skinlibrary.utils.SkinFileUtils;

import static cn.leftshine.readme.utils.ImgTool.tintDrawable;

public class NewsDetailActivity extends BaseActivity {

    private static WebView webView;
    private TextView tv_newsInfo_subtitle,tv_newsInfo_source,tv_newsInfo_original,tv_newsInfo_author,tv_newsInfo_title,tv_newsInfo_toolbar_title;
    private ImageButton ib_newsDetail_collect;
    private CollapsingToolbarLayout cToolBar_newsInfo;
    private NestedScrollView news_detail_nestedScrollView;
    private AppBarLayout appbar;
    private RelativeLayout rl_newsDetail_bottomBar,progress_layer;
    private LinearLayout ll_news_detail_news_content;
    private boolean isTitleShow=false;
    private boolean isBottomBarShow=true;
    private boolean isCollected = false;
    private SettingsHelper settingsHelper;
    private Context context;
    private Snackbar snackbar;

    private static ArrayList<String> imgList ;

    public static ArrayList<String> getImgList() {
        return imgList;
    }
    public static WebView getView() {
        return webView;
    }

    @Override
    protected void init() {
        context = this;
        settingsHelper = new SettingsHelper(context);
        /*if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Window window = getWindow();
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS
                    | WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            //获取样式中的属性值
            TypedValue typedValue = new TypedValue();
            this.getTheme().resolveAttribute(android.R.attr.colorPrimary, typedValue, true);
            int[] attribute = new int[] { android.R.attr.colorPrimary };
            TypedArray array = this.obtainStyledAttributes(typedValue.resourceId, attribute);
            int color = array.getColor(0, Color.TRANSPARENT);
            array.recycle();

            window.setStatusBarColor(color);
        }*/
        super.init();
    }

    @Override
    protected int setLayoutResourceID() {
        return R.layout.activity_news_detail;
    }

    @Override
    protected void initView() {
        Toolbar toolbar = $(R.id.toolbar_news_detail);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);//左侧添加一个默认的返回图标
        getSupportActionBar().setHomeButtonEnabled(true); //设置返回键可用

        webView= $(R.id.wv_news_content);
        tv_newsInfo_subtitle = $(R.id.tv_newsInfo_subtitle);
        tv_newsInfo_title = $(R.id.tv_newsInfo_title);
        tv_newsInfo_toolbar_title = $(R.id.tv_newsInfo_toolbar_title);
        /*tv_newsInfo_source = $(R.id.tv_newsInfo_source);
        tv_newsInfo_original = $(R.id.tv_newsInfo_original);
        tv_newsInfo_author = $(R.id.tv_newsInfo_author);*/
        cToolBar_newsInfo =$(R.id.cToolBar_newsInfo);
        news_detail_nestedScrollView  = $(R.id.news_detail_nestedScrollView);
        rl_newsDetail_bottomBar = $(R.id.rl_newsDetail_bottomBar);
        //暂时去掉底栏
        rl_newsDetail_bottomBar.setVisibility(View.GONE);
        ib_newsDetail_collect = $(R.id.ib_newsDetail_collect);
        progress_layer = $(R.id.progress_layer);
        ll_news_detail_news_content = $(R.id.ll_news_detail_news_content);

        ViewGroup.MarginLayoutParams vlp = (ViewGroup.MarginLayoutParams) tv_newsInfo_title.getLayoutParams();
        final int offsetValue =vlp.topMargin;
        appbar = $(R.id.appbar);
        dynamicAddView(appbar,"background",R.color.color_content_bg);
        dynamicAddView(news_detail_nestedScrollView,"background",R.color.color_content_bg);
        appbar.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
            @Override
            public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
                Log.i("pcj", "onOffsetChanged: verticalOffset="+verticalOffset);
                if (Math.abs(verticalOffset) <offsetValue&&isTitleShow) {
                    tv_newsInfo_toolbar_title.animate().alpha(0f).start();
                    isTitleShow=false;
                } else if (Math.abs(verticalOffset) >= offsetValue&&!isTitleShow) {
                    tv_newsInfo_toolbar_title.animate().alpha(1f).start();
                    isTitleShow = true;
                }
            }
        });
        news_detail_nestedScrollView.setSmoothScrollingEnabled(true);
        news_detail_nestedScrollView.setOnScrollChangeListener(new NestedScrollView.OnScrollChangeListener() {
            @Override
            public void onScrollChange(NestedScrollView v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
                Log.i("pcj", "onScrollChange:" +
                        "\nonlyChildHeight="+ll_news_detail_news_content.getHeight() +
                        "\nscrollY+nestedScrollView.Height()="+(news_detail_nestedScrollView.getHeight()+scrollY) +
                        "\nscrollY-oldScrollY="+(scrollY-oldScrollY));
                //上滑
                if(scrollY-oldScrollY > 0 ){  //向上滑
                    Log.i("pcj", "onScrollChange: 向上滑");

                    if(ll_news_detail_news_content.getHeight() <= scrollY+news_detail_nestedScrollView.getHeight()&&!isBottomBarShow){  //滑到底部
                        Log.i("pcj", "onScrollChange: 滑到底");
                        rl_newsDetail_bottomBar.animate().cancel();
                        rl_newsDetail_bottomBar.animate().translationY(0).start();
                        isBottomBarShow = true;
                    }else if(isBottomBarShow){
                        rl_newsDetail_bottomBar.animate().cancel();
                        rl_newsDetail_bottomBar.animate().translationY(rl_newsDetail_bottomBar.getHeight()).start();
                        isBottomBarShow =false;
                    }
                }else if(scrollY-oldScrollY < 0 && !isBottomBarShow){  //向下滑
                    Log.i("pcj", "onScrollChange: 向下滑");
                    rl_newsDetail_bottomBar.animate().cancel();
                    rl_newsDetail_bottomBar.animate().translationY(0).start();
                    isBottomBarShow = true;
                }

            }
        });

        ib_newsDetail_collect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Drawable icon_collect_drawable = getResources().getDrawable(R.mipmap.icon_collect);
                if(isCollected){    //已收藏
                    ib_newsDetail_collect.setImageDrawable(tintDrawable(icon_collect_drawable, ColorStateList.valueOf(getResources().getColor(R.color.icon_origin))));
                    isCollected=false;
                }else { //未收藏
                    ib_newsDetail_collect.setImageDrawable(tintDrawable(icon_collect_drawable, ColorStateList.valueOf(getResources().getColor(R.color.colorPrimary))));
                    isCollected=true;
                }
            }
        });
        snackbar  = Snackbar.make(webView,"",Snackbar.LENGTH_SHORT);

        dynamicAddView(snackbar.getView(),"background",R.color.colorAccent);
    }

    @Override
    protected void initData() {
        Intent intent = getIntent();
        String title = intent.getStringExtra("title");
        String link = intent.getStringExtra("link");
        String pubDate = intent.getStringExtra("pubDate");
        String content = intent.getStringExtra("content");
        imgList = intent.getStringArrayListExtra("imgList");

        getSupportActionBar().setTitle(title);
        getSupportActionBar().setDisplayShowTitleEnabled(false);
        cToolBar_newsInfo.setTitle(title);
        tv_newsInfo_title.setText(title);
        tv_newsInfo_toolbar_title.setText(title);
        tv_newsInfo_toolbar_title.setAlpha(0);
        isTitleShow=false;
        //tv_newsInfo_toolbar_title.setVisibility(View.GONE);
        if(pubDate !=null) {
            final Date isoDate = DateTool.isoStrParseToDate(pubDate);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            tv_newsInfo_subtitle.setText(sdf.format(isoDate));
        }
        //content=content.replace("<img", "<img height=\"100%\" width=\"250px\"");

        WebSettings webSettings = webView.getSettings();//获取webview设置属性
        webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);//把html中的内容放大webview等宽的一列中
        webSettings.setJavaScriptEnabled(true);//支持js
        //webSettings.setBuiltInZoomControls(true); // 显示放大缩小
        //webSettings.setSupportZoom(true); // 可以缩放
        webView.addJavascriptInterface(new JavaScriptInterface(this), "imagelistner");//这个是给图片设置点击监听的，如果你项目需要webview中图片，点击查看大图功能，可以这么添加
        webView.setWebViewClient(new MyWebViewClient());
        String htmlData = HTMLTool.createHtmlDate(title,content,link);
        webView.loadDataWithBaseURL("file:///android_asset/html/", htmlData, "text/html" , "utf-8", null);
        webView.setWebContentsDebuggingEnabled(true);
    }

    @Override
    protected void beforDestroy() {

    }
    

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_news_detail,menu);
        if (menu != null) {
            if (menu.getClass() == MenuBuilder.class) {
                try {
                    Method m = menu.getClass().getDeclaredMethod("setOptionalIconsVisible", Boolean.TYPE);
                    m.setAccessible(true);
                    m.invoke(menu, true);
                } catch (Exception e) {

                }
            }
        }
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()){
            case android.R.id.home:
                finish();
            case R.id.action_news_detail_night_mode:
                setNightMode(!settingsHelper.isNightMode());
                /*if(settingsHelper.isNightMode()){
                    //关闭夜间模式
                    settingsHelper.setNightmode(false);
                    switchNightModeCss(false);
                    SkinManager.getInstance().restoreDefaultTheme();

                }else{
                    //开启夜间模式
                    //加载皮肤时有个判断，所以需要先设置nightMode为true，若切换失败再设为false
                    settingsHelper.setNightmode(true);
                    SkinManager.getInstance().loadSkin("night_mode",
                            new SkinLoaderListener() {
                                @Override
                                public void onStart() {
                                }

                                @Override
                                public void onSuccess() {
                                    switchNightModeCss(true);
                                    Toast.makeText(getApplicationContext(), "切换成功", Toast.LENGTH_SHORT).show();
                                }

                                @Override
                                public void onFailed(String errMsg) {
                                    //切换夜间模式失败，把设置值重置为false
                                    settingsHelper.setNightmode(false);
                                    Toast.makeText(getApplicationContext(), "切换失败:"+errMsg, Toast.LENGTH_SHORT).show();
                                }

                                @Override
                                public void onProgress(int progress) {
                                    Log.i("Theme", "onProgress: "+progress);
                                }

                            }
                    );
                }*/
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    private void switchNightModeCss(boolean b) {
        final int version = Build.VERSION.SDK_INT;
// 因为该方法在 Android 4.4 版本才可使用，所以使用时需进行版本判断
        String js = "javascript:switchNightMode(" + b + ")";
        if (version < 18) {
            webView.loadUrl(js);
        } else {
            webView.evaluateJavascript(js, new ValueCallback<String>() {
                @Override
                public void onReceiveValue(String value) {
                    //此处为 js 返回的结果
                }
            });
        }
    }

    private class MyWebViewClient extends WebViewClient {
        //ProgressDialog progressDialog = new ProgressDialog();
        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
            progress_layer.setAlpha(1f);
            //progress_layer.setVisibility(View.GONE);
            //progress_layer.setVisibility(View.VISIBLE);
            getWindow().setFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE,WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            imgReset();//重置webview中img标签的图片大小
            // html加载完成之后，添加监听图片的点击js函数
            addImageClickListner();
            progress_layer.animate().setDuration(500).alpha(0f).start();
           // progress_layer.setVisibility(View.GONE);
            getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
        }


        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            if(!url.startsWith("tbopen"))
                view.loadUrl(url);
            return true;
        }
        private void imgReset() {
            webView.loadUrl("javascript:(function(){" +
                    "var objs = document.getElementsByTagName('img'); " +
                    "for(var i=0;i<objs.length;i++)  " +
                    "{"
                    + "var img = objs[i];   " +
                    "    img.style.maxWidth = '100%'; img.style.height = 'auto'; img.style.align='center' " +
                    "}" +
                    "})()");
        }
        private void addImageClickListner() {
            webView.loadUrl("javascript:(function(){" +
                    "var objs = document.getElementsByTagName(\"img\"); " +
                    "for(var i=0;i<objs.length;i++)  " +
                    "{"
                    + "    objs[i].onclick=function()  " +
                    "    {  "
                    + "        window.imagelistner.openImage(this.src);  " +
                    "    }  " +
                    "}" +
                    "})()");
        }
    }
    public static class JavaScriptInterface {
        private static Context mContext;
        private static TextView tv_download_progress;
        private static DownLoadProgressbar pb_download;

        public JavaScriptInterface(Context context) {
            this.mContext = context;
        }


        //点击图片回调方法
        //必须添加注解,否则无法响应
        @JavascriptInterface
        public void openImage(String img) {
            Log.i("TAG", "响应点击事件!");
             /*Intent intent = new Intent();
            intent.putExtra("image", img);
            //intent.setClass(context, BigImageActivity.class);//BigImageActivity查看大图的类，自己定义就好
            Toast.makeText(context,img,Toast.LENGTH_SHORT).show();
            context.startActivity(intent);*/

            final ArrayList<String> imgSrcList = getImgList();
            int tmpIndex = 0;
            for (int i = 0;i<imgSrcList.size();i++){
                if (imgSrcList.get(i).equals(img)){
                    tmpIndex = i;
                    break;
                }
            }
            final int index = tmpIndex;

            ImageBrowserConfig.TransformType transformType = ImageBrowserConfig.TransformType.Transform_Default;
            ImageBrowserConfig.IndicatorType indicatorType = ImageBrowserConfig.IndicatorType.Indicator_Number;
            ImageBrowserConfig.ScreenOrientationType screenOrientationType = ImageBrowserConfig.ScreenOrientationType.Screenorientation_Default;
            Boolean showCustomShadeView = true;
            Boolean showCustomProgressView =true;
            final View customView = LayoutInflater.from(mContext).inflate(R.layout.layout_custom_image_show_view, null);
            ImageView ic_close = (ImageView) customView.findViewById(R.id.iv_close);
            ImageView iv_more = (ImageView) customView.findViewById(R.id.iv_more);
                    /*
                    ImageView iv_comment = (ImageView) customView.findViewById(R.id.iv_comment);
                    ImageView iv_zan = (ImageView) customView.findViewById(R.id.iv_zan);
                    ImageView iv_delete = (ImageView) customView.findViewById(R.id.iv_delete);*/
            final ImageView iv_download = customView.findViewById(R.id.iv_download);
            ImageView iv_share = customView.findViewById(R.id.iv_share);
            final TextView tv_number_indicator = (TextView) customView.findViewById(R.id.tv_number_indicator);
            tv_download_progress  = customView.findViewById(R.id.tv_download_progress);
            pb_download = customView.findViewById(R.id.pb_download);
            pb_download.setVisibility(View.INVISIBLE);
            tv_download_progress.setVisibility(View.INVISIBLE);
            ic_close.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    //关闭图片浏览
                    MNImageBrowser.finishImageBrowser();
                }
            });
            iv_more.setVisibility(View.GONE);
            iv_more.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    FragmentActivity currentActivity = MNImageBrowser.getCurrentActivity();
                    ImageView currentImageView = MNImageBrowser.getCurrentImageView();
                    if (currentImageView != null && currentActivity != null) {
                        //showListDialog(currentActivity, currentImageView);
                    }
                }
            });

            iv_download.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    downloadImageWithShare(mContext,imgSrcList.get(index),false);
                }
            });
            iv_share.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    downloadImageWithShare(mContext,imgSrcList.get(index),true);
                }
            });
                    /*iv_delete.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            //删除当前位置的图片
                            MNImageBrowser.removeCurrentImage();
                            //刷新指示器
                            tv_number_indicator.setText((MNImageBrowser.getCurrentPosition() + 1) + "/" + MNImageBrowser.getImageList().size());
                        }
                    });*/
            tv_number_indicator.setText((index + 1) + "/" + imgSrcList.size());
            MNImageBrowser.with(mContext)
                    //必须-当前位置
                    .setCurrentPosition(index)
                    //必须-图片加载用户自己去选择
                    .setImageEngine(new GlideImageEngine())
                    //必须（setImageList和setImageUrl二选一，会覆盖）-图片集合
                    .setImageList(imgSrcList)
                    //必须（setImageList和setImageUrl二选一，会覆盖）-设置单张图片
                    //.setImageUrl("xxx")
                    //非必须-图片切换动画
                    .setTransformType(transformType)
                    //非必须-指示器样式（默认文本样式：两种模式）
                    .setIndicatorType(indicatorType)
                    //设置隐藏指示器
                    .setIndicatorHide(false)
                    //设置自定义遮盖层，定制自己想要的效果，当设置遮盖层后，原本的指示器会被隐藏
                    .setCustomShadeView(showCustomShadeView ? customView : null)
                    //自定义ProgressView，不设置默认默认没有
                    .setCustomProgressViewLayoutID(showCustomProgressView ? R.layout.layout_custom_progress_view : 0)
                    //非必须-屏幕方向：横屏，竖屏，Both（默认：横竖屏都支持）
                    .setScreenOrientationType(screenOrientationType)
                    //非必须-图片单击监听
                    .setOnClickListener(new OnClickListener() {
                        @Override
                        public Boolean onClick(FragmentActivity activity, ImageView view, int position, String url) {
                            //单击监听
                            Log.i("Image", "onClick: ");
                            if(customView.getVisibility()==View.VISIBLE){
                                customView.setVisibility(View.INVISIBLE);
                            }else{
                                customView.setVisibility(View.VISIBLE);
                            }
                            //返回一个布尔值决定单击图片是否关闭浏览
                            return false;
                        }
                    })

                    //非必须-图片长按监听
                    .setOnLongClickListener(new OnLongClickListener() {
                        @Override
                        public void onLongClick(FragmentActivity activity, ImageView imageView, int position, String url) {
                            //长按监听
                            Log.i("Image", "onLongClick: ");
                            if(customView.getVisibility()==View.VISIBLE){
                                customView.setVisibility(View.INVISIBLE);
                            }else{
                                customView.setVisibility(View.VISIBLE);
                            }
                        }
                    })

                    //页面切换监听
                    .setOnPageChangeListener(new OnPageChangeListener() {
                        @Override
                        public void onPageSelected(int position) {
                            //Log.i(TAG, "onPageSelected:" + position);
                            if (tv_number_indicator != null) {
                                tv_number_indicator.setText((position + 1) + "/" + MNImageBrowser.getImageList().size());
                                tv_download_progress.setVisibility(View.INVISIBLE);
                                pb_download.setVisibility(View.INVISIBLE);
                            }
                        }
                    })
                    //全屏模式：默认全屏模式
                    .setFullScreenMode(true)
                    //打开
                    .show(getView());
        }
        public static void downloadImageWithShare(final Context context, final String src, final Boolean isWithShare){
            AndPermission.with(context)
                    .runtime()
                    .permission(Permission.Group.STORAGE)
                    .onGranted(new Action() {
                        @Override
                        public void onAction(Object data) {
                            //保存图片
                        /*String saveDir = isWithShare?SkinFileUtils.getCacheDir(context)+File.separator+"Images":Environment.getExternalStorageDirectory()+File.separator+ Environment.DIRECTORY_DCIM +File.separator+"ReadMeImages";*/
                            final String saveDir = Environment.getExternalStorageDirectory()+ File.separator+ Environment.DIRECTORY_DCIM +File.separator+"readme_images";
                            final String cacheDir = SkinFileUtils.getCacheDir(context) + File.separator + "images";
                            final String fileName = FileUtils.get().getNameFromUrl(src);
                            File saveFile = new File(saveDir,fileName);
                            if(saveFile.exists()){
                                if (isWithShare){
                                    shareImage(saveFile);
                                }else{
                                    //询问是否重新下载，是就继续，否则return退出
                                    new AlertDialog.Builder(MNImageBrowserActivity.getCurrentActivity())
                                            .setTitle("文件已存在！")
                                            .setMessage("是否重新下载？")
                                            .setNegativeButton("否", new DialogInterface.OnClickListener() {
                                                @Override
                                                public void onClick(DialogInterface dialog, int which) {
                                                }
                                            })
                                            .setPositiveButton("是", new DialogInterface.OnClickListener() {
                                                @Override
                                                public void onClick(DialogInterface dialog, int which) {
                                                    startDownload(src, saveDir,fileName,isWithShare);
                                                }
                                            })
                                            .show();
                                }
                            }else{
                                if(isWithShare) {
                                    File cacheFile = new File(cacheDir, fileName);
                                    if (cacheFile.exists()) {
                                        shareImage(cacheFile);
                                    }else{
                                        startDownload(src, cacheDir,fileName,isWithShare);
                                    }
                                }else{
                                    startDownload(src, saveDir,fileName,isWithShare);
                                }
                            }

                        }
                    })
                    .onDenied(new Action() {
                        @Override
                        public void onAction(Object data) {
                            Toast.makeText(context,"权限获取失败",Toast.LENGTH_SHORT).show();
                        }
                    })
                    .start();
        }

        private static void startDownload(String src, String saveDir, String fileName, final Boolean isWithShare) {
            pb_download.setVisibility(View.VISIBLE);
            tv_download_progress.setVisibility(View.VISIBLE);
            FileUtils.get().download(src, saveDir,fileName, new FileUtils.OnDownloadListener() {
                @Override
                public void onDownloadSuccess(File file) {
                    //Toast.makeText(MyApplication.getContext(),"已保存到："+path,Toast.LENGTH_SHORT).show();

                    //tv_download_progress.setText(R.string.image_download_success);
                    Message msg = uiHandler.obtainMessage();
                    msg.what=0;
                    msg.obj = isWithShare;
                    uiHandler.sendMessage(msg);
                    if(isWithShare){
                        shareImage(file);
                    }else {
                        MNImageBrowser.getCurrentActivity().sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(file)));    // 发送广播，通知刷新图库的显示
                        Snackbar.make(tv_download_progress,"已保存到："+file.getPath(),Snackbar.LENGTH_SHORT).show();
                    }
                }

                @Override
                public void onDownloading(int progress) {
                    Log.i("download", "onDownloading: "+progress);
                    //Snackbar.make(iv_download,"下载中："+progress+"%",Snackbar.LENGTH_SHORT).show();
                    //tv_download_progress.setText(context.getString(R.string.image_download_progress)+progress+"%");
                    Message msg = uiHandler.obtainMessage();
                    msg.what=1;
                    msg.arg1=progress;
                    msg.obj = isWithShare;
                    uiHandler.sendMessage(msg);
                    pb_download.setProgress(progress);
                }

                @Override
                public void onDownloadFailed() {
                    //Toast.makeText(MyApplication.getContext(),"保存失败",Toast.LENGTH_SHORT).show();
                    //Snackbar.make(tv_download_progress,"下载失败",Snackbar.LENGTH_SHORT).show();

                    //tv_download_progress.setText(R.string.image_download_fail);
                    Message msg = uiHandler.obtainMessage();
                    msg.what=2;
                    msg.obj = isWithShare;
                    uiHandler.sendMessage(msg);
                }
            });
        }

        private static void shareImage(File file) {
            Intent intent = new Intent();
            intent.setAction(Intent.ACTION_SEND);
            intent.setType("image/*");
            Uri uri;
            if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.N){
                intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                uri = FileProvider.getUriForFile(MNImageBrowser.getCurrentActivity(), "cn.leftshine.readme.fileprovider",file);
            }else{
                uri = Uri.fromFile(file);
            }
            intent.putExtra(Intent.EXTRA_STREAM, uri);
            intent = Intent.createChooser(intent,"分享到：");
            MNImageBrowser.getCurrentActivity().startActivity(intent);
            //MNImageBrowser.getCurrentActivity().startActivityForResult(intent,0);
        }


        /*构造一个Handler，主要作用有：1）供非UI线程发送Message  2）处理Message并完成UI更新*/
        public static Handler uiHandler=new Handler(new Handler.Callback() {
            @Override
            public boolean handleMessage(Message msg) {
                Boolean isWithShare = (Boolean)msg.obj;
                switch (msg.what){
                    case 0:
                        tv_download_progress.setText(isWithShare?R.string.image_prepare_success:R.string.image_download_success);
                        break;
                    case 1:
                        tv_download_progress.setText(isWithShare?mContext.getString(R.string.image_prepare_progress)+msg.arg1+"%":mContext.getString(R.string.image_download_progress)+msg.arg1+"%");
                        break;
                    case 2:
                        tv_download_progress.setText(isWithShare?R.string.image_prepare_fail:R.string.image_download_fail);
                        break;
                    default:
                        break;

                }
                return false;
            }
        });


    }





    private void setNightMode(boolean night) {
        if (night){
            settingsHelper.setNightmode(true);
            SkinManager.getInstance().loadSkin("night_mode",
                    new SkinLoaderListener() {
                        @Override
                        public void onStart() {
                        }

                        @Override
                        public void onSuccess() {
                            //Toast.makeText(getApplicationContext(), "切换成功", Toast.LENGTH_SHORT).show();
                            switchNightModeCss(true);
                            showSnackbar(getString(R.string.tip_night_mode_on));
                        }

                        @Override
                        public void onFailed(String errMsg) {
                            settingsHelper.setNightmode(false);
                            //Toast.makeText(getApplicationContext(), "切换失败:"+errMsg, Toast.LENGTH_SHORT).show();
                            showSnackbar(getString(R.string.tip_night_mode_fail));
                        }

                        @Override
                        public void onProgress(int progress) {
                            Log.i("Theme", "onProgress: "+progress);
                        }

                    }
            );
        }else {
            //night mode off
            settingsHelper.setNightmode(false);
            //SkinManager.getInstance().restoreDefaultTheme();
            String lastSkinFilename = settingsHelper.getLastThemeFilename();
            if (lastSkinFilename.equals(ThemeInfoHelper.DEFAULT_SKIN_FILE_NAME)) {
                SkinManager.getInstance().restoreDefaultTheme();
                switchNightModeCss(false);
            } else {
                SkinManager.getInstance().loadSkin(lastSkinFilename,
                        new SkinLoaderListener() {
                            @Override
                            public void onStart() {
                            }

                            @Override
                            public void onSuccess() {
                                //Toast.makeText(getApplicationContext(), getString(R.string.tip_theme_switch_success,skinName), Toast.LENGTH_SHORT).show();
                                switchNightModeCss(false);
                                showSnackbar(getString(R.string.tip_night_mode_off));
                            }

                            @Override
                            public void onFailed(String errMsg) {
                                //Toast.makeText(getApplicationContext(), getString(R.string.tip_theme_switch_fail, skinName), Toast.LENGTH_SHORT).show();
                                settingsHelper.setNightmode(true);
                                showSnackbar(getString(R.string.tip_night_mode_fail));
                            }

                            @Override
                            public void onProgress(int progress) {
                                Log.i("Theme", "onProgress: " + progress);
                            }

                        }
                );
            }
        }
    }

    private void showSnackbar(String tip) {
        snackbar.setText(tip);
        snackbar.show();
    }
}
